<template>
  <div class="app-container">
    <el-row>
      <el-col :span="19">
        <div class="filter-container">
          <el-autocomplete
            v-model="listQuery.name"
            class="inline-input"
            :fetch-suggestions="querySearch"
            :trigger-on-focus="false"
            placeholder="检索产品名称"
            @select="handleFilter"
          />
          <el-select
            v-model="listQuery.brand_id"
            class="full-width"
            filterable
            clearable
            placeholder="请选择品牌"
          >
            <el-option
              v-for="brand in brands"
              :key="brand.id"
              :label="brand.name"
              :value="brand.id"
            />
          </el-select>
          <el-button type="primary" icon="el-icon-search" @click="handleFilter">
            搜索
          </el-button>
        </div>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" @click="openCreateDialog(null)">创建产品</el-button>
      </el-col>
      <el-col :span="2" :offset="1">
        <el-button type="success" @click="createBrandVisible = true">创建品牌</el-button>
      </el-col>
    </el-row>
    <el-table
      v-loading.body="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
    >
      <el-table-column align="center" prop="id" label="ID" width="80" sortable="custom">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="名称" sortable="custom" prop="name">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="出售价格">
        <template slot-scope="scope">
          <span>{{ scope.row.sale_price }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="品牌">
        <template slot-scope="scope">
          <span>{{ scope.row.brand ? scope.row.brand.name: '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="更新时间">
        <template slot-scope="scope">
          <span>{{ scope.row.update_time }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="openCreateDialog(scope.row.id)">修改</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        background
        :current-page="listQuery.page"
        :page-sizes="[20, 50, 100]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!--创建产品-->
    <el-dialog
      title="创建产品"
      :visible.sync="createDialogVisible"
    >
      <el-form ref="form" :model="form" label-width="140px">
        <el-form-item label="名称">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="进货价格">
          <el-input v-model="form.purchase_price" />
        </el-form-item>
        <el-form-item label="出售价格">
          <el-input v-model="form.sale_price" />
        </el-form-item>
        <el-form-item label="排序值">
          <el-input v-model="form.sort" />
        </el-form-item>
        <el-form-item label="品牌">
          <el-select
            v-model="form.brand_id"
            class="full-width"
            filterable
            placeholder="请选择品牌"
          >
            <el-option
              v-for="brand in brands"
              :key="brand.id"
              :label="brand.name"
              :value="brand.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="createDialogVisible = false">取 消</el-button>
        <el-button v-loading="createProductLoading" type="primary" @click="handleCreateProduct">确 定</el-button>
      </span>
    </el-dialog>

    <!--创建品牌-->
    <el-dialog
      title="创建品牌"
      :visible.sync="createBrandVisible"
    >
      <el-form ref="form" :model="brandForm">
        <el-form-item label="名称">
          <el-input v-model="brandForm.name" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="createBrandVisible = false">取 消</el-button>
        <el-button v-loading="createBrandLoading" type="primary" @click="handleCreateBrand">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getList, querySearch, create, update, findById, deleteById } from '@/api/product'
import { all as getAllBrand, create as createBrand } from '@/api/brand'

export default {
  name: 'ProductList',
  data() {
    return {
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined,
        brand_id: undefined,
        prop: undefined,
        order: undefined
      },
      submitLoading: false,
      brands: [],
      createDialogVisible: false,
      form: {},
      createProductLoading: false,
      createBrandVisible: false,
      createBrandLoading: false,
      brandForm: {}
    }
  },
  created() {
    this.getList()
    this.getAllBrand()
  },
  methods: {
    getList() {
      this.listLoading = true
      getList(this.listQuery).then((response) => {
        this.listLoading = false
        const { data } = response
        this.list = data.data
        this.total = data.total
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleFilter() {
      this.getList()
    },
    getAllBrand() {
      getAllBrand().then((response) => {
        this.brands = response.data
      })
    },
    querySearch(queryString, cb) {
      querySearch({ keyword: queryString }).then((response) => {
        const result = []
        if (response.data) {
          response.data.forEach((item) => {
            result.push({
              value: item.name
            })
          })
        }

        cb(result)
      })
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}`
        ? 'ascending'
        : sort === `-${key}`
          ? 'descending'
          : ''
    },
    sortChange(data) {
      const { prop, order } = data
      this.listQuery.prop = prop
      this.listQuery.order = order
      this.getList()
    },
    openCreateDialog(id) {
      if (id) {
        this.fetchData(id)
      } else {
        this.form = {}
      }

      this.createDialogVisible = true
    },
    handleCreateProduct() {
      this.createProductLoading = true

      if (this.form.id) {
        update(this.form.id, this.form).then(resp => {
          this.$message.success(resp.message)
        }).finally(() => {
          this.createProductLoading = false
          this.createDialogVisible = false
          this.getList()
        })
      } else {
        create(this.form).then(resp => {
          this.$message.success(resp.message)
        }).finally(() => {
          this.createProductLoading = false
          this.createDialogVisible = false
          this.getList()
        })
      }
    },
    fetchData(id) {
      findById(id).then((response) => {
        this.form = response.data
      })
    },
    handleDelete(id) {
      this.$confirm('是否确定删除?', '提示').then(() => {
        console.log('deleting')
        deleteById(id).then(resp => {
          this.$message.success(resp.message)
        }).finally(() => {
          this.getList()
        })
      })
    },
    handleCreateBrand() {
      this.createBrandLoading = true
      createBrand(this.brandForm).then(resp => {
        this.$message.success(resp.message)
      }).finally(() => {
        this.createBrandLoading = false
        this.createBrandVisible = false
      })
    }
  }
}
</script>
